package com.hubu.parking.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hubu.parking.constant.ParkConstant;
import com.hubu.parking.entity.park.ParkingRecord;
import com.hubu.parking.entity.park.ParkingReservation;
import com.hubu.parking.entity.park.ParkingSpot;
import com.hubu.parking.mapper.ParkingSpotMapper;
import com.hubu.parking.model.dto.park.OrderSpotDto;
import com.hubu.parking.model.dto.park.PageListSpotRequest;
import com.hubu.parking.model.enums.LogicStatusEnum;
import com.hubu.parking.model.enums.SpotStatusEnum;
import com.hubu.parking.model.vo.KeyValue;
import com.hubu.parking.service.ParkingRecordService;
import com.hubu.parking.service.ParkingReservationService;
import com.hubu.parking.service.ParkingSpotService;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 19468
 * @description 针对表【parking_spot(停车场车位信息表)】的数据库操作Service实现
 * @createDate 2025-03-02 16:52:08
 */
@Service
public class ParkingSpotServiceImpl extends ServiceImpl<ParkingSpotMapper, ParkingSpot> implements ParkingSpotService {

    @Resource
    private ParkingReservationService parkingReservationService;

    @Resource
    @Lazy
    private ParkingRecordService recordService;

    @Override
    public Page<ParkingSpot> pageListParkingSpot(PageListSpotRequest pageRequest) {
        Page<ParkingSpot> page = new Page<>();
        page.setCurrent(pageRequest.getCurrent());
        page.setSize(pageRequest.getPageSize());
        LambdaQueryWrapper<ParkingSpot> queryWrapper = new LambdaQueryWrapper<>();
        Integer status = pageRequest.getStatus();
        if (ObjectUtil.isNotNull(SpotStatusEnum.getEnumByValue(status))) {
            queryWrapper.eq(ParkingSpot::getStatus, pageRequest.getStatus());
        }
        String spotNumber = pageRequest.getSpotNumber();
        if (StrUtil.isNotBlank(spotNumber)) {
            queryWrapper.like(ParkingSpot::getSpotNumber, spotNumber);
        }
        String location = pageRequest.getLocation();
        if (StrUtil.isNotBlank(location)) {
            queryWrapper.like(ParkingSpot::getLocation, location);
        }
        return this.page(page, queryWrapper);
    }

    @Override
    public List<ParkingSpot> listParkingSpot(PageListSpotRequest pageRequest) {
        LambdaQueryWrapper<ParkingSpot> queryWrapper = new LambdaQueryWrapper<>();
        Integer status = pageRequest.getStatus();
        if (ObjectUtil.isNotNull(SpotStatusEnum.getEnumByValue(status))) {
            queryWrapper.eq(ParkingSpot::getStatus, pageRequest.getStatus());
        }
        String location = pageRequest.getLocation();
        if (StrUtil.isNotBlank(location)) {
            queryWrapper.like(ParkingSpot::getLocation, location);
        }
        String spotPrefix = pageRequest.getSpotPrefix();
        if (StrUtil.isNotBlank(spotPrefix)) {
            queryWrapper.likeRight(ParkingSpot::getSpotNumber, spotPrefix);
        }
        return this.list(queryWrapper);
    }

    @Override
    public List<String> listPartition() {
        return baseMapper.listPartition();
    }

    @Override
    public List<KeyValue<Integer>> listStatus() {
        List<KeyValue<Integer>> keyValues = new ArrayList<>();
        for (Integer value : SpotStatusEnum.getValues()) {
            LambdaQueryWrapper<ParkingSpot> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ParkingSpot::getStatus, value);
            Long count = baseMapper.selectCount(queryWrapper);
            KeyValue<Integer> keyValue = new KeyValue<>();
            keyValue.setKey(SpotStatusEnum.getEnumByValue(value).getDesc());
            keyValue.setValue(count.intValue());
            keyValues.add(keyValue);
        }
        return keyValues;
    }

    @Override
    public Boolean orderSpot(OrderSpotDto orderSpotDto) {
        // 1.校验
        if (orderSpotDto == null) {
            return false;
        }
        Integer spotId = orderSpotDto.getSpotId();
        Integer userId = orderSpotDto.getUserId();
        if (spotId == null || userId == null) {
            return false;
        }
        LambdaQueryWrapper<ParkingReservation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ParkingReservation::getUserId, userId);
        queryWrapper.eq(ParkingReservation::getStatus, LogicStatusEnum.UN_AVAILABLE.getValue());
        List<ParkingReservation> reservations = parkingReservationService.list(queryWrapper);
        LambdaQueryWrapper<ParkingRecord> recordQueryWrapper = new LambdaQueryWrapper<>();
        recordQueryWrapper.eq(ParkingRecord::getUserId, userId);
        recordQueryWrapper.eq(ParkingRecord::getStatus, LogicStatusEnum.UN_AVAILABLE.getValue());
        List<ParkingRecord> records = recordService.list(recordQueryWrapper);
        if (!reservations.isEmpty() || !records.isEmpty()) {
            return false;
        }
        // 2.预订 可用 -> 已预约
        UpdateWrapper<ParkingSpot> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", spotId).set("status", SpotStatusEnum.RESERVED.getValue());
        this.update(updateWrapper);

        // 3.更新预定表
        ParkingReservation parkingReservation = new ParkingReservation();
        parkingReservation.setUserId(userId);
        parkingReservation.setSpotId(spotId);
        Date reservationTime = new Date();
        parkingReservation.setReservationTime(reservationTime);
        parkingReservation.setEndTime(getSpotReleaseTime(reservationTime));
        parkingReservationService.save(parkingReservation);

        return true;
    }

    @Override
    public Boolean quickOrderSpot(OrderSpotDto orderSpotDto) {
        // 1.校验
        if (orderSpotDto == null) {
            return false;
        }
        // 找到最近的车位
        ParkingSpot nearSpot = getNearSpot();
        if (nearSpot == null) {
            return false;
        }
        Integer nearSpotId = nearSpot.getId();
        orderSpotDto.setSpotId(nearSpotId);
        return orderSpot(orderSpotDto);
    }

    /**
     * 获取最近的车位
     * @return 车位
     */
    @Override
    public ParkingSpot getNearSpot() {
        LambdaQueryWrapper<ParkingSpot> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ParkingSpot::getStatus, SpotStatusEnum.AVAILABLE.getValue());
        List<ParkingSpot> spots = this.list(queryWrapper);
        if (spots.isEmpty()) {
            return null;
        }
        ParkingSpot result = spots.get(0);
        for (ParkingSpot spot : spots) {
            String location = spot.getLocation();
            int newValue = Integer.parseInt(location);
            int oldValue = Integer.parseInt(result.getLocation());
            if (newValue < oldValue) {
                result = spot;
            }
        }
        return result;
    }

    /**
     * 获取车位施放时间
     *
     * @return 时间
     */
    public Date getSpotReleaseTime(Date reservationTime) {
        long time = reservationTime.getTime();
        long endTime = time + ParkConstant.RELEASE_TIME;
        return new Date(endTime);
    }
}




